package controller.util;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
import modelo.bo.cmd.*;
import modelo.dto.EEntidade;
import modelo.util.factory.FactoryControllerHelper;
import controller.helper.IControllerHelper;

public class FacadeController {
	private static HttpServletRequest request;
	private static HttpServletResponse response;
	private static EICommand eICmd;
	private static EEntidade eEntidade;
	private static IControllerHelper ich;
	private static ICommand cmd; 
		
	public static String executar(HttpServletRequest req, HttpServletResponse resp) 
		throws ServletException, IOException, SQLException{			
		
		FacadeController.request = req;
		FacadeController.response = resp;
		
		criarControllerHelper(request, response);			
		executarCommand();
		
		return retornarPagina();
	}
	
	private static void criarControllerHelper(HttpServletRequest request, HttpServletResponse response) {				
		eICmd = EICommand.valueOf(request.getParameter("cmd"));
        eEntidade = EEntidade.valueOf(request.getParameter("entidade"));        
        ich = FactoryControllerHelper.getControllerHelper(eEntidade);    
	}
	
	private static void executarCommand()
		throws ServletException, IOException, SQLException {
		
        cmd = ich.getICommand(eICmd);
        cmd.init(request);
		cmd.executar(request, response);		
	}
	
	private static String retornarPagina() {
		return cmd.retornaPagina();
	}
	
	public static void dispacharPagina(String pagina) 
		throws ServletException, IOException {
		
        RequestDispatcher rd = request.getRequestDispatcher(pagina);
        rd.forward(request, response);
		
	}
}
